import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from apps.article.serializers import ListArticleSerializer
from apps.question.serializers import GetAllLableSerializer, QuestionSerializer, ReplySerializerForList
from apps.recruit.serializer import CompanySerializer
from .models import User
from apps.question.models import Label

class CreateUserSerializer(serializers.ModelSerializer):
    '''
    创建用户
    '''
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    token = serializers.CharField(label='token', read_only=True)

    class Meta:
        model = User
        # fields = ('id', 'username', 'password', 'sms_code', 'mobile', 'token', 'avatar')
        fields = '__all__'
        extra_kwargs = {
            'username': {
                'min_length': 2,
                'max_length': 20,
                'error_messages': {
                    'min_length': '用户名字符长度最小为2，最大为20',
                    'max_length': '用户名字符长度最小为2，最大为20',
                }
            },
            'password': {
                'min_length': 8,
                'max_length': 20,
                'write_only': True,
                'error_messages': {
                    'min_length': '密码字符长度最小为8，最大为20',
                    'max_length': '密码字符长度最小为8，最大为20',

                }
            },
        }

    def validate(self, attrs):
        # 验证手机号
        mobile = attrs['mobile']
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError('手机号格式错误')

        # 验证短信验证码
        conn = get_redis_connection('verify')
        real_sms_code = conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('验证码无效')
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('验证码错误')
        return attrs

    def create(self, validated_data):
        '''
        重写保存方法，为客户密码加密
        :param validated_data:
        :return:
        '''
        del validated_data['sms_code']

        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()

        # 签发token
        jwt_payload = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload(user)
        token = jwt_encode(payload)

        user.token = token
        return user


class UserInfoSerializer(serializers.ModelSerializer):
    '''
    用户信息
    '''
    username = serializers.CharField(read_only=True)
    labels = GetAllLableSerializer(many=True, read_only=True)
    questions = QuestionSerializer(many=True, read_only=True)
    answer_question = ReplySerializerForList(many=True, read_only=True)
    collected_articles = ListArticleSerializer(many=True, read_only=True)
    enterpises = CompanySerializer(many=True, read_only=True)
    recruits = CompanySerializer(many=True, read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'realname', 'birthday', 'sex', 'avatar', 'website', 'email', 'city', 'address', 'labels', 'questions', 'answer_question', 'collected_articles', 'enterpises','recruits')
        # fields = '__all__'


class UserPasswordSerializer(serializers.ModelSerializer):
    '''
    修改密码
    '''

    class Meta:
        model = User
        fields = ('password',)
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def update(self, instance, validated_data):
        user = super().update(instance, validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

class UserLabelSerializer(serializers.ModelSerializer):
    """
    用户修改擅长技术
    """
    labels = serializers.PrimaryKeyRelatedField(required=True, many=True, queryset=Label.objects.all())
    class Meta:
        model = User
        fields = ('id', 'labels')